﻿#region File Info Header
/*________________________________________________________________________________________

  Copyright (C) 2011 Jason Zhang, eagleboost@msn.com

  * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
  * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
  * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.

________________________________________________________________________________________*/
#endregion File Info Header

namespace EagleBoost.Wpf.Presentation.Converters
{
  using System;
  using System.Globalization;
  using System.Windows.Data;

  /// <summary>
  /// Convert the decimal value to string by using parameter as a string format and convert the string back to decimal value
  /// </summary>
  [ValueConversion(typeof(double), typeof(string), ParameterType = typeof(string))]
  public class NumericFormatConverter : ConverterMarkupExtension<NumericFormatConverter>, IValueConverter
  {
    #region IValueConverter Members
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      var format = parameter as string;
      return !string.IsNullOrEmpty(format) ? string.Format(format, value) : value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      double result;
      return double.TryParse(value as string, out result) ? result : 0;
    }
    #endregion IValueConverter Members
  }
}
